package com.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {
        //初始化信号量为 3，每次只有3个线程执行
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new Thread(new RequestTask(semaphore, "请求任务" + i)).start();
        }
    }

    static class RequestTask implements Runnable{
        Semaphore semaphore;
        String taskName;

        public RequestTask(Semaphore semaphore, String taskName) {
            this.semaphore = semaphore;
            this.taskName = taskName;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(taskName + "任务执行中...");
                TimeUnit.SECONDS.sleep(2);
                System.out.println(taskName + "任务执行完成...");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
